package myjava.d_time;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * @Auther: cty
 * @Date: 2019/11/6 下午8:33
 * @Description: 测试Calendar类（日期类）的使用   Calendar类的主要用途是对指定日期进行处理运算！
 * 
 * 日期对象————>时间对象————>时间戳
 * Calendar cal = GregorianCalendar();
 * Date date = cal.getTime();
 * long stamp = date.getTime();
 * 
 * 时间戳————>时间对象————>日期对象
 * long stamp = System.currentTimeMillis();
 * Date date = new Date(stamp);
 * Calendar cal = GregorianCalendar();
 * cal.setTime(date);
 *
 * @version: 1.0
 */
public class C_TestCalendar {
    public static void main(String[] args) {
        //获得日期相关元素
        Calendar calendar = new GregorianCalendar(2999,10,9,22,10,50);
        System.out.println(calendar);  //res: java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=false,...
        int year = calendar.get(Calendar.YEAR);
        System.out.println(year);  //res: 2999
        int month = calendar.get(Calendar.MONTH);  //0-11分别代表1-12月
        System.out.println(month);  //res: 10
        int date = calendar.get(Calendar.DATE);  //或用：DAY_OF_MONTH
        System.out.println(date);  //res: 9
        int weekday = calendar.get(Calendar.DAY_OF_WEEK);  //1-7分别代表周日、周一至周六
        System.out.println(weekday);  //res: 7

        //设置日期的相关元素
        Calendar c2 = new GregorianCalendar();  //默认是当前日期时间
        System.out.println(c2);  //res: ...YEAR=2020...
        c2.set(Calendar.YEAR,9012);  
        System.out.println(c2);  //res: ...YEAR=9012...

        //日期的计算
        Calendar c3 = new GregorianCalendar();
        c3.add(Calendar.DATE,100);  //再过100天后日期时间
        System.out.println(c3);
        c3.add(Calendar.YEAR,-100);  //100年前的日期时间
        System.out.println(c3);

        //日期对象和时间对象的转化
        Date d4 = c3.getTime();  //将日期对象转化为时间对象
        System.out.println(d4);

        Calendar c4 = new GregorianCalendar();
        c4.setTime(d4);  //将时间对象转化为日期对象
        System.out.println(c4);

        pritCalendar(c4);
    }

    public static void pritCalendar(Calendar c){
        //打印格式：2019年11月6日 21:17:00 周3
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH)+1;
        int date = c.get(Calendar.DATE);

        int hour = c.get(Calendar.HOUR);
        int minute = c.get(Calendar.MINUTE);
        int second = c.get(Calendar.SECOND);

        int dayweek = c.get(Calendar.DAY_OF_WEEK)-1;
        String week = (dayweek==0)?"日":(""+dayweek);
        System.out.println(year+"年"+month+"月"+date+"日 "+hour+"时"+minute+"分"+second+"秒 周"+week);
    }
}
